package com.androsz.andslr.app;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.androsz.andslr.R;

public abstract class HostActivity extends AnalyticActivity {

	boolean alreadyPrepared = false;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		CharSequence thistit = getTitle();
		CharSequence thattit = item.getTitle();
		int bleh = getActionBar().getDisplayOptions()
				& ActionBar.DISPLAY_HOME_AS_UP;
		if (thistit == thattit)
			if (bleh == ActionBar.DISPLAY_HOME_AS_UP)
				finish();
			else if (bleh == 0) {
				final Intent intent = new Intent(this, ImportActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		switch (item.getItemId()) {
		case R.id.settings:
			// TODO
			// startActivity(new Intent(this, SettingsActivity.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { final
	 * MenuInflater inflater = getMenuInflater();
	 * inflater.inflate(R.menu.host_menu, menu); return
	 * super.onCreateOptionsMenu(menu); }
	 */

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (!alreadyPrepared) {
			final MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.host_menu, menu);
			alreadyPrepared = true;
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onResume() {
		// ActionBar bar = getActionBar();
		// bar.setDisplayHomeAsUpEnabled(true);
		// bar.setDisplayShowHomeEnabled(true);
		super.onResume();
	}

	private List<WeakReference<AnalyticFragment>> fragList = new ArrayList<WeakReference<AnalyticFragment>>();

	@Override
	public void onAttachFragment(Fragment fragment) {
		try {
			fragList.add(new WeakReference<AnalyticFragment>(
					(AnalyticFragment) fragment));
		} catch (ClassCastException cce) {

		}
		super.onAttachFragment(fragment);
	}

	public List<AnalyticFragment> getActiveAnalyticFragments() {
		ArrayList<AnalyticFragment> ret = new ArrayList<AnalyticFragment>();
		for (WeakReference<AnalyticFragment> ref : fragList) {
			AnalyticFragment f = ref.get();
			if (f != null && f.isVisible()) {
				ret.add(f);
			}
		}
		return ret;
	}

	public void onClick(View v) {
		List<AnalyticFragment> activeAnalyticFragments = getActiveAnalyticFragments();
		for (AnalyticFragment af : activeAnalyticFragments) {
			af.onClick(v);
		}
	}
}
